<template>
  <div id="wrap">
    <h1>案例-学生成绩管理系统</h1>
    <div>
      <div class="main">
        <div class="overview">班级平均年龄: {{ avgAge }}</div>
        <div class="tools-header">
          <div>
            <button class="openModalBtn" @click="addStudent">新增学生信息</button>
            <button class="openModalBtn" @click="delSelectedStudent">删除选中学生</button>
          </div>
          <div>
            <input
              v-model="keyword"
              type="text"
              name="keyword"
              class="keyword"
              placeholder="Search by name"
            />
            <button @click="generateSearchData" type="button" class="searchBtn">Search</button>
          </div>
        </div>

        <table class="studentTable">
          <thead>
            <tr>
              <th>
                <input
                  @change="changeSelectedAll"
                  type="checkbox"
                  class="selectAll"
                  v-model="isAllSelect"
                />
              </th>
              <th>ID</th>
              <th>Name</th>
              <th>Gender</th>
              <th>Hobbies</th>
              <th>Email</th>
              <th>Phone</th>
              <th>Age</th>
              <th>Created At</th>
              <th>Updated At</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <!-- Student rows will be added dynamically here -->
            <tr v-for="item in searchStudentArr" :key="item.id">
              <td>
                <input
                  @change="changeSelectedItem"
                  type="checkbox"
                  class="selectAll"
                  v-model="item.selected"
                />
              </td>
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.gender }}</td>
              <td>{{ item.hobbies }}</td>
              <td>{{ item.email }}</td>
              <td>{{ item.phone }}</td>
              <td>{{ item.age }}</td>
              <td>{{ item.create_at }}</td>
              <td>{{ item.update_at }}</td>
              <td>
                <a @click="delStuInfo(item)" href="javascript:void(0)">删除</a>
                <a @click="editStuInfo(item)" href="javascript:void(0)">修改</a>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- Modal for adding/editing students -->
        <div v-show="isShowModel" class="studentModal modal" @click="closeModel">
          <div class="modal-content" @click.stop>
            <h3 class="modalTitle">{{ modelInfo.title }}</h3>
            <form class="studentForm">
              <input v-model="stuFormDate.id" type="hidden" class="studentIdToEdit" />

              <label for="studentName">Name</label>
              <input
                v-model="stuFormDate.name"
                type="text"
                name="name"
                class="studentName"
                required
              />

              <label for="studentGender">Gender</label>
              <select
                v-model="stuFormDate.gender"
                name="gender"
                class="studentGender"
                placeholder="请选择性别..."
                required
              >
                <option value="Male">Male</option>
                <option value="Female">Female</option>
              </select>

              <label for="studentHobbies">Hobbies</label>
              <input
                v-model="stuFormDate.hobbies"
                type="text"
                name="hobbies"
                class="studentHobbies"
                required
              />

              <label for="studentEmail">Email</label>
              <input
                v-model="stuFormDate.email"
                type="email"
                name="email"
                class="studentEmail"
                required
              />

              <label for="studentPhone">Phone</label>
              <input
                v-model="stuFormDate.phone"
                type="text"
                name="phone"
                class="studentPhone"
                required
              />

              <label for="studentAge">Age</label>
              <input
                v-model="stuFormDate.age"
                type="number"
                name="age"
                class="studentAge"
                required
              />

              <button @click.prevent="saveStuInfo" type="button" class="saveStudentBtn">
                Save Student
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'dayStuDemo36',
};
</script>

<script lang="ts" setup>
import { computed, ref } from 'vue';
import { getNowDateTime } from '@/utils/index.ts';
import { uniqueId } from 'lodash';
/*---------------------------------------------------------------弹窗控制----------------------------------------------------------------- */
//控制弹窗的显示与隐藏
const isShowModel = ref(false);
//点击关闭弹窗
const closeModel = () => {
  isShowModel.value = false;
};

/*---------------------------------------------------------------虚拟数据----------------------------------------------------------------- */
const studentArr = ref([
  {
    id: 1,
    name: 'Alice',
    gender: 'Female',
    hobbies: 'Reading',
    email: 'alice@example.com',
    phone: '12345678901',
    age: 20,
    create_at: getNowDateTime(),
    update_at: getNowDateTime(),
  },
  {
    id: 2,
    name: 'Bob',
    gender: 'Male',
    hobbies: 'Sports',
    email: 'bob@example.com',
    phone: '10987654321',
    age: 22,
    create_at: getNowDateTime(),
    update_at: getNowDateTime(),
  },
]);
//初始化
function initAction() {
  generateSearchData();
}
/*---------------------------------------------------------------增加学生信息----------------------------------------------------------------- */
//学生信息接口
interface IStudent {
  id: number;
  name: string;
  gender: string;
  hobbies: string;
  email: string;
  phone: string;
  age: number | string;
  create_at?: string;
  update_at?: string;
  selected?: boolean;
}
//绑定新增学信息的输入框数据
const stuFormDate = ref<IStudent>({
  id: 1,
  name: '小明',
  gender: 'Female',
  hobbies: '唱跳rap',
  email: '7635572389@qq.com',
  phone: '13659486423',
  age: 18,
  selected: false,
});
//增加学生信息的功能
const saveStuInfo = () => {
  //判断是修改还是添加
  if (modelInfo.value.type === 'add') {
    //添加学生信息：1、生成学上id  2、把学生信息追加到学生数组中
    stuFormDate.value.id = uniqueId('newStu_');
    console.log(stuFormDate.value);
    studentArr.value.push({
      ...JSON.parse(JSON.stringify(stuFormDate.value)),
      create_at: getNowDateTime(),
      update_at: getNowDateTime(),
    });
    closeModel();
  } else {
    console.log(stuFormDate.value, '修改学生信息');
    //完善点击保存，实现数据修改
    stuFormDate.value.update_at = getNowDateTime(); //更新时间
    //修改学生信息
    const index = studentArr.value.findIndex((i) => i.id === stuFormDate.value.id);
    studentArr.value[index] = JSON.parse(JSON.stringify(stuFormDate.value));
  }
  changeSelectedItem();
  generateSearchData();
  closeModel();
};
/*---------------------------------------------------------------平均年龄的计算----------------------------------------------------------------- */
const avgAge = computed(() => {
  return Math.round(
    studentArr.value.reduce(
      (previousValue, currentValue) => previousValue + Number(currentValue.age),
      0,
    ) / studentArr.value.length,
  );
});
/*---------------------------------------------------------------实现修改动态修改头部标题----------------------------------------------------------------- */
const modelInfo = ref({
  type: 'add',
  title: '添加学生信息',
});
/*---------------------------------------------------------------点击判断是否是弹窗----------------------------------------------------------------- */
//点击显示弹窗
const addStudent = () => {
  //绑定新增学信息的输入框数据
  stuFormDate.value = {
    id: 1,
    name: '小明',
    gender: 'Male',
    hobbies: '唱跳rap',
    email: '7635572389@qq.com',
    phone: '13659486423',
    age: 18,
    create_at: getNowDateTime(),
    update_at: getNowDateTime(),
  };
  modelInfo.value.type = 'add';
  modelInfo.value.title = '添加学生信息';
  isShowModel.value = true;
};
//修改学生信息
const editStuInfo = (stu: IStudent) => {
  modelInfo.value.type = 'edit';
  modelInfo.value.title = '修改学生信息';
  stuFormDate.value = JSON.parse(JSON.stringify(stu));
  isShowModel.value = true;
};

/*---------------------------------------------------------------实现删除功能----------------------------------------------------------------- */
const delStuInfo = (item: IStudent) => {
  const index = studentArr.value.findIndex((i) => i.id === item.id);
  studentArr.value.splice(index, 1);
  generateSearchData();
  changeSelectedItem();
};

/*---------------------------------------------------------------实现检索功能----------------------------------------------------------------- */
const searchStudentArr = ref<Array<IStudent>>([]); //搜索后的用来装数据的空数组
const keyword = ref(''); //查空
//实现检索
const generateSearchData = () => {
  searchStudentArr.value = studentArr.value.filter((i) => i.name.includes(keyword.value));
  console.log(studentArr.value);
  console.log(searchStudentArr.value);
};
/*---------------------------------------------------------------全选与单选 且 实现选中部分删除----------------------------------------------------------------- */
//是否全选
const isAllSelect = ref(false);
const changeSelectedAll = (event: Event) => {
  const checked = (event.target as HTMLInputElement).checked;
  console.log(checked);
  if (checked) {
    searchStudentArr.value.forEach((item: IStudent) => {
      item.selected = true;
    });
  } else {
    searchStudentArr.value.forEach((item: IStudent) => {
      item.selected = false;
    });
  }
};
//修改选中
const changeSelectedItem = () => {
  if (searchStudentArr.value.length > 0) {
    // 只有当所有项都被选中时，isAllSelect 才为 true
    isAllSelect.value = searchStudentArr.value.every((i: IStudent) => {
      console.log(i.selected);
      return i.selected;
    });
  } else {
    isAllSelect.value = false;
  }
};
//选中的学生删除操作
const delSelectedStudent = () => {
  searchStudentArr.value.forEach((i) => {
    if (i.selected) {
      delStuInfo(i);
      generateSearchData();
    }
  });
};
/*---------------------------------------------------------------初始化----------------------------------------------------------------- */
//初始化
initAction();
</script>

<style lang="scss">
@use './style/StuDemo36.scss';
</style>
